<?php

class PushComponent
{
    const DEVICE_TYPE_ANDROID = 3;// Android
    const DEVICE_TYPE_IOS = 4;// iOS
    public $error = array();
    public $device_type = NULL;
    public $merchant_params;

    /**
     * [__construct description]
     * @param [type] $apiKey    [description]
     * @param [type] $secretKey [description]
     * openssl pkcs12 -in MyApnsCert.p12 -out MyApnsCert.pem -nodes
     */
    public function __construct($merchant_params, $debug = false)
    {
        Yii::import('ext.xmpush.Constants');
        Yii::import('ext.xmpush.Sender');
        Yii::import('ext.xmpush.Builder');
        Yii::import('ext.xmpush.HttpBase');
        Yii::import('ext.xmpush.MiMessage');
        Yii::import('ext.xmpush.Result');
        Yii::import('ext.xmpush.ErrorCode');
        Yii::import('ext.xmpush.IOSBuilder');
        Yii::import('ext.xmpush.Stats');
        Yii::import('ext.xmpush.Tracer');
        Yii::import('ext.xmpush.PushRequestPath');
        Yii::import('ext.xmpush.PushRequestType');
        Yii::import('ext.xmpush.ServerSwitch');
        Yii::import('ext.xmpush.Server');

        $this->merchant_params = $merchant_params;
        if (isset($merchant_params['package'])) {
            Constants::setPackage($merchant_params['package']);
            $this->device_type = self::DEVICE_TYPE_ANDROID;
        } else {
            Constants::setBundleId($merchant_params['bundle']);
            $this->device_type = self::DEVICE_TYPE_IOS;
            if ($debug) {
                Constants::useSandbox();
            } else {
                Constants::useOfficial();
            }
        }
        Constants::setSecret($merchant_params['secret']);
    }

    /**
     * @param $params
     * title
     * description
     * @param array $extra
     */
    public function pushToAllIOS($params, $extra = array())
    {
        $result = false;
        $sender = new Sender();
        $message = new IOSBuilder();
        if (isset($params['description'])) {
            $message->title($params['title']);
            $message->body($params['description']);
        } else {
            $message->description($params['title']);
        }
        $message->soundUrl('default');
//        $message->soundUrl('newmessage');
        $message->badge('1');
        foreach ($extra as $key => $value) {
            $message->extra($key, $value);
        }
//        $message->extra('payload', json_encode($params));
        $message->build();

        $response = $sender->broadcastAll($message);

        $notify = array();
        $notify['merchant_params'] = $this->merchant_params;
        $notify['params'] = $params;
        $notify['response'] = $response->getRaw();
        file_put_contents(Yii::app()->getRuntimePath() . '/mipush_request_' . date("Y_W") . '.log', sprintf("%s %s %s", date("Y-m-d H:i:s"), json_encode($notify), PHP_EOL), FILE_APPEND);

        if ($response->getErrorCode() == 0) {
            $result = true;
        }
        return $result;
    }

    public function pushToAllAndroid($params, $extra = array())
    {
        $result = false;
        $sender = new Sender();
        $message = new Builder();
        $message->title($params['title']);  // 通知栏的title
        $message->description($params['description']); // 通知栏的descption
        $message->passThrough(0);  // 这是一条通知栏消息，如果需要透传，把这个参数设置成1,同时去掉title和descption两个参数
//        $message->payload($payload); // 携带的数据，点击后将会通过客户端的receiver中的onReceiveMessage方法传入。
        $message->extra(Builder::notifyForeground, 1); // 应用在前台是否展示通知，如果不希望应用在前台时候弹出通知，则设置这个参数为0
        $message->notifyId(2); // 通知类型。最多支持0-4 5个取值范围，同样的类型的通知会互相覆盖，不同类型可以在通知栏并存
        $message->build();
        $response = $sender->broadcastAll($message);

        $notify = array();
        $notify['merchant_params'] = $this->merchant_params;
        $notify['params'] = $params;
        $notify['response'] = $response->getRaw();
        file_put_contents(Yii::app()->getRuntimePath() . '/mipush_request_' . date("Y_W") . '.log', sprintf("%s %s %s", date("Y-m-d H:i:s"), json_encode($notify), PHP_EOL), FILE_APPEND);

        if ($response->getErrorCode() == 0) {
            $result = true;
        }
        return $result;
    }

    public function pushToUserIos($push_user_id, $params, $extra = array())
    {
        $result = false;
        $message = new IOSBuilder();
        if (isset($params['description'])) {
            $message->title($params['title']);
            $message->body($params['description']);
        } else {
            $message->description($params['title']);
        }
        if (isset($extra['sound_url'])) {
            $message->soundUrl($extra['sound_url']);
        } else {
            $message->soundUrl('default');
        }
        if (isset($extra['badge'])) {
            $message->badge($extra['badge']);
        }
        foreach ($extra as $key => $value) {
            $message->extra($key, $value);
        }
//        $message->extra('payload', json_encode($extra));
        $message->build();

        $sender = new Sender();
        $response = $sender->send($message, $push_user_id);

        $notify = array();
        $notify['merchant_params'] = $this->merchant_params;
        $notify['params'] = $params;
        $notify['response'] = $response->getRaw();
        file_put_contents(Yii::app()->getRuntimePath() . '/mipush_request_' . date("Y_W") . '.log', sprintf("%s %s %s", date("Y-m-d H:i:s"), json_encode($notify), PHP_EOL), FILE_APPEND);

        if ($response->getErrorCode() == 0) {
            $result = true;
        }
        return $result;
    }

    public function pushToUserAndroid($push_user_id, $params, $extra = array())
    {
        $result = false;
//        $payload = json_encode($intent);
        $sender = new Sender();
        $message2 = new Builder();
        $message2->title($params['title']);
        $message2->description($params['description']);
        $message2->passThrough(0);
        $message2->payload(json_encode($extra));
        $message2->extra(Builder::notifyForeground, 1);
        if (isset($extra['sound_url'])) {
            $message2->extra(Builder::soundUri, 'android.resource://' . $this->merchant_params['package'] . $extra['sound_url']);
        }
        $message2->notifyId(0);
        $message2->build();

        $response = $sender->send($message2, $push_user_id);

        $notify = array();
        $notify['merchant_params'] = $this->merchant_params;
        $notify['params'] = $params;
        $notify['response'] = $response->getRaw();
        file_put_contents(Yii::app()->getRuntimePath() . '/mipush_request_' . date("Y_W") . '.log', sprintf("%s %s %s", date("Y-m-d H:i:s"), json_encode($notify), PHP_EOL), FILE_APPEND);

        if ($response->getErrorCode() == 0) {
            $result = true;
        }
        return $result;
    }
}
